﻿using System;
using System.Collections.Generic;

using Fuse8.DomainFramework.Domain;
using Fuse8.DomainFramework.Common;
using Fuse8.DomainFramework.Configuration;

namespace Fuse8.ContentManagementFramework.DataAccess
{
    public static class CmsDataRepositoryConfiguration
    {
        private static Dictionary<string, string> _repositoryConfigurations = new Dictionary<string, string>();

        public static string DefineConnectionString(Type typeFor)
        {
            Guard.ArgumentNotNull(typeFor, "typeFor");
            
            return _repositoryConfigurations.ContainsKey(GenerateEntityKey(typeFor)) ?
                _repositoryConfigurations[GenerateEntityKey(typeFor)] :
                DataRepositoryConfiguration.SqlConnectionString;
        }

        public static void RegisterConnectionString<TEntity>(string connectionString)
            where TEntity : class, IEntityObject
        {
            RegisterConnectionString(typeof(TEntity), connectionString);
        }

        public static void RegisterConnectionString(Type typeFor, string connectionString)
        {
            Guard.ArgumentNotNull(typeFor, "typeFor");
            Guard.ArgumentNotEmpty(connectionString, "connectionString");

            string entityKey = GenerateEntityKey(typeFor);
            
            lock (_repositoryConfigurations)
            {                
                if (_repositoryConfigurations.ContainsKey(entityKey))
                {
                    _repositoryConfigurations[entityKey] = connectionString;
                }
                else
                {
                    _repositoryConfigurations.Add(entityKey, connectionString);
                }
            }
        }

        private static string GenerateEntityKey(Type typeFor)
        {
            return typeFor.FullName;
        }
    }
}
